var express = require('express');
var router = express.Router();
var Movie = require('../models/movie');
var Travel = require('../models/travel');
var Picture = require('../models/picture');
var User = require('../models/user');
var Cart = require('../models/cart');
var Order = require('../models/order');
var Commodity = require('../models/commodity');

var _ = require('underscore');
var mongoose = require('mongoose');

var fs = require('fs')
var path = require('path')

var middleware = require('../routes/middleware')

var shop = require('../controllers/shop')



//用户注册
router.get('/register', function(req, res, next){
  req.session.error = "";
  res.render('register', { 
    title: '注册'
  });

})
router.get('/login', function(req, res, next){
  res.render('login', { 
    title: '登录'
  })
})
router.post('/user/signup', function(req, res, next){
  var _user = {
    name:req.body.name,
    password:req.body.password,
    email:req.body.email,
    tel:req.body.tel
  };

  User.findOne({name: _user.name}, function(err, user){
    
    if(err){
      console.log(err)
    }
    if(user){
      req.session.error = '用户名已存在！';
      res.send(500);
      
    }else{
      var user = new User(_user)
      user.save(function(err, user){
        if(err){
          console.log(err)
        }
        req.session.error = '用户名创建成功,请登录！';
        res.redirect("/login")
      })
    }
  })
  
})

//用户列表页
router.get('/admin/userlist', middleware.signinRequired, middleware.adminRequired, function(req, res, next) {
  
    User.fetch(function(err, users) {
      if(err){
        console.log(err)
      }
      res.render('userlist', {
        title: '用户列表页',
        users: users
      });
    })
  
});
//删除用户
router.delete('/admin/userlist', middleware.signinRequired, middleware.adminRequired, function(req,res,next){
  var id = req.query.id;
    
    if(id){
        User.remove({_id:id},function(err,movie){
            if(err){
               console.log(err);
            }else{
                res.json({success:1});
            }
        });
    }
  
})

//登录
router.post('/user/signin', function(req, res){
  
  var name = req.body.name
  var password = req.body.password
  User.findOne({name: name}, function(error, user){
    if(error) {
      res.send(500);
      console.log(err)
    }
    if(!user){
      // res.send('用户不存在');
      res.send(404);
    }
    else if(password != user.password){
      // res.send('密码错误');
      res.send(404);
      
    }else{
      req.session.user = user;
      res.send(200);
    }
  })
})




//logout
router.get('/logout', function(req, res){
  delete req.session.user
  res.redirect('/')
})
//用户详情
router.get('/userdetail', function(req, res, next) {

    User.findById(req.session.user._id , function(err, userdetail) {
      if(err){
        console.log(err)
      }
      res.render('userdetail', {
        title: '用户详情页',
        userdetail: userdetail
      });
    })
    
});
//用户详情
router.get('/userdetail/:id', function(req, res, next) {
    var id = req.params.id
    User.findById(id , function(err, userdetail) {
      console.log(userdetail)
      if(err){
        console.log(err)
      }
      res.render('userdetail', {
        title: '用户详情页',
        userdetail: userdetail
      });
    })
    
});

router.get('/userupdata', function(req, res, next) {

    User.findById(req.session.user._id , function(err, userdetail) {
      if(err){
        console.log(err)
      }
      res.render('userupdata', {
        title: '用户详情页',
        userdetail: userdetail
      });
    })
    
});
router.get('/userupdata/:id', function(req, res, next) {
    var id = req.params.id
    User.findById(id , function(err, userdetail) {
      if(err){
        console.log(err)
      }
      res.render('userupdata', {
        title: '用户详情页',
        userdetail: userdetail
      });
    })
    
});

//更改用户信息
router.post('/updataUser' ,function(req,res, next){
    var id = req.session.user._id;
    
    var userObj = req.body;
    var _user;
    User.findById(id, function(err, user) {
      console.log(user)
      if (err) {
        console.log(err);
      };
      _user = _.extend(user, userObj);
      
      _user.save(function(err, user) {
        if (err) {
          console.log(err);
        }
        res.redirect('/userdetail');
      });
    });
});

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { 
      title: '首页'
    })
});

/* GET about page. */
router.get('/about', function(req, res, next) {
    res.render('about', { 
      title: '关于'
    })
});



//新闻

//新闻首页
router.get('/newsindex', function(req, res, next) {
  Movie.fetch(function(err, movies){
  	if (err) {
  		console.log(err)
  	}
  	res.render('newsindex', { 
	  	title: '新闻首页', 
	  	movies: movies

	  })
  })
  
});

//新闻详情页
router.get('/movie/:id', function(req, res, next) {
  
  var id = req.params.id

  Movie.findById(id, function(err, movie) {
    if(err){
      console.log(err)
    }
    res.render('newsdetail', { 
      title: '新闻详情页',
      movie: movie
    })
    
    
  })
  
});

//新闻后台录入页
router.get('/admin/movie', middleware.signinRequired, middleware.adminRequired, function(req, res, next) {
  
    res.render('newsadmin', { 
      title: '新闻后台录入页',
      movie :{
        author: "",
        title: "",
        text: "",
        poster: "",
        type: "",
        tag:""
      } 
    });
  
  
});

//新闻更新
router.get('/update/:id', middleware.signinRequired, middleware.adminRequired, function(req, res, next){
  var id =req.params.id
  
    if(id) {
      Movie.findById(id, function(err, movie){
        res.render('newsadmin', {
          title: '新闻后台更新页',
          movie: movie
        })
      })
    }
  
})

//新闻删除
router.delete('/admin/list', middleware.signinRequired, middleware.adminRequired, function(req,res,next){
  var id = req.query.id;
    
    if(id){
        Movie.remove({_id:id},function(err,movie){
            if(err){
               console.log(err);
            }else{
                res.json({success:1});
            }
        });
    }
  
})

// //新闻录入页

router.post('/admin/movie/new', middleware.signinRequired, middleware.adminRequired, middleware.savePoster, function(req, res, next) {

  
    var id = req.body.id;
    var movieObj = req.body;
    var _movie;
      if (req.poster) {
        movieObj.poster = req.poster
        console.log(req.poster)
      }

      

      if (id) {
        Movie.findById(id, function(err, movie) {
          if (err) {
            console.log(err);
          }
          _movie = _.extend(movie, movieObj);
          
          _movie.save(function(err, movie) {
            if (err) {
              console.log(err);
            }
            res.redirect('/movie/' + movie._id);
          });
        });
      } else {
        _movie = new Movie({

          title: movieObj.title,
          text: movieObj.text,
          type: movieObj.type,
          poster: movieObj.poster,
          tag: movieObj.tag,
          author: movieObj.author,

        });
        _movie.save(function(err, movie) {
          if (err) {
            console.log(err);
          }
          res.redirect('/movie/' + movie._id);
          
        });
      }
    

  
});


//新闻列表页
router.get('/admin/list', middleware.signinRequired, middleware.adminRequired, function(req, res, next) {
  
    Movie.fetch(function(err, movies) {
      if(err){
        console.log(err)
      }
      res.render('newslist', {
        title: '新闻后台列表页',
        movies: movies
      });
    })
  
});





//图片

/* GET home page. */
router.get('/pictureindex', function(req, res, next) {

  Picture.fetch(function(err, pictures){
    if (err) {
      console.log(err)
    }
    res.render('pictureIndex', { 
      title: '图片首页', 
      pictures: pictures

    })
  })
  
});

//后台录入页
router.get('/admin/picture', middleware.signinRequired, middleware.adminRequired, function(req, res, next) {
  
    res.render('pictureAdmin', { 
      title: '图片后台录入页',
      picture :{
        title: "",
        poster: "",
        summary: "",
        author:""
      } 
    });
  
  
});

//admin update movie
router.get('/pictureUpdate/:id', middleware.signinRequired, middleware.adminRequired, function(req, res, next){
  var id =req.params.id
  
    if(id) {
      Picture.findById(id, function(err, picture){
        res.render('pictureAdmin', {
          title: '图片后台更新页',
          picture: picture
        })
      })
    }
  
})

//admin delete movie
router.delete('/admin/picturelist',middleware.signinRequired, middleware.adminRequired, function(req,res,next){
  var id = req.query.id;
  
    if(id){
        Picture.remove({_id:id},function(err,picture){
            if(err){
               console.log(err);
            }else{
                res.json({success:1});
            }
        });
    }
  
})

// //后台录入页
// //admin post movie

//admin post movie
router.post('/admin/picture/new', middleware.signinRequired, middleware.adminRequired, middleware.savePoster, function(req, res, next) {

  
    var id = req.body.id;
    var movieObj = req.body;
    var _movie;
      if (req.poster) {
        movieObj.poster = req.poster
        console.log(req.poster)
      }
      if (id) {
        Picture.findById(id, function(err, movie) {
          if (err) {
            console.log(err);
          }
          _movie = _.extend(movie, movieObj);
          
          _movie.save(function(err, movie) {
            if (err) {
              console.log(err);
            }
            res.redirect('/pictureindex');
          });
        });
      } else {
        _movie = new Picture({

          title: movieObj.title,
          author:movieObj.tag,
          
          poster: movieObj.poster,
          summary: movieObj.summary

        });
        _movie.save(function(err, movie) {
          if (err) {
            console.log(err);
          }
          res.redirect('/pictureindex');
          
        });
      }
    

  
});


//列表页
router.get('/admin/picturelist',middleware.signinRequired, middleware.adminRequired, function(req, res, next) {
  
    Picture.fetch(function(err, pictures) {
      if(err){
        console.log(err)
      }
      res.render('picturelist', {
        title: '图片后台列表页',
        pictures: pictures
      });
    })
  
});



//游记
/* GET home page. */
router.get('/travelIndex', function(req, res, next) {
  console.log('user in session:')
  console.log(req.session.user)
  Travel.fetch(function(err, travels){
    if (err) {
      console.log(err)
    }
    res.render('travelIndex', { 
      title: '游记首页', 
      travels: travels

    })
  })
  
});

//详情页
router.get('/travel/:id', function(req, res, next) {
  
  var id = req.params.id

  Travel.findById(id, function(err, travel) {
    if(err){
      console.log(err)
    }
    res.render('travelDetail', { 
      title: '游记详情页',
      travel: travel
    })
    
    
  })
  
});

//后台录入页
router.get('/admin/travel',middleware.signinRequired, middleware.adminRequired, function(req, res, next) {
  
    res.render('travelAdmin', { 
      title: '游记后台录入页',
      travel :{
        author:"",
        title: "",
        text: "",
        poster: "",
        type: "",
        tag:""
      } 
    });
  
  
});

//admin update movie
router.get('/travelUpdate/:id',middleware.signinRequired, middleware.adminRequired, function(req, res, next){
  var id =req.params.id
  
    if(id) {
      Travel.findById(id, function(err, travel){
        res.render('travelAdmin', {
          title: '游记后台更新页',
          travel: travel
        })
      })
    }
 
})

//admin delete movie
router.delete('/admin/travelList',middleware.signinRequired, middleware.adminRequired, function(req,res,next){
  var id = req.query.id;

  
    if(id){
        Travel.remove({_id:id},function(err,travel){
            if(err){
               console.log(err);
            }else{
                res.json({success:1});
            }
        });
    }
  
})

// //后台录入页
// //admin post movie

//admin post movie
router.post('/admin/travel/new', middleware.signinRequired, middleware.adminRequired, middleware.savePoster, function(req, res, next) {

  
    var id = req.body.id;

    var travelObj = req.body;
    var _travel;
      if (req.poster) {
        travelObj.poster = req.poster
        console.log(req.poster)
      }
      if (id) {
        Travel.findById(id, function(err, travel) {
          if (err) {
            console.log(err);
          }
          _travel = _.extend(travel, travelObj);
          
          _travel.save(function(err, travel) {
            if (err) {
              console.log(err);
            }
            res.redirect('/travel/' + travel._id);
          });
        });
      } else {
        _travel = new Travel({

          title: travelObj.title,
          text: travelObj.text,
          type: travelObj.type,
          poster: travelObj.poster,
          tag: travelObj.tag,
          author:travelObj.author
        });
        _travel.save(function(err, travel) {
          if (err) {
            console.log(err);
          }
          res.redirect('/travel/' + travel._id);
          
        });
      }
    

  
});


//列表页
router.get('/admin/travelList',middleware.signinRequired, middleware.adminRequired, function(req, res, next) {
  
    Travel.fetch(function(err, travels) {
      if(err){
        console.log(err)
      }
      res.render('travelList', {
        title: '游记后台列表页',
        travels: travels
      });
    })
  
});




//购物商城





//查看购物车商品
router.get('/cart', middleware.signinRequired, function(req, res) {
    
    
        Cart.find({"uId":req.session.user._id,"cStatus":false}, function (error, docs) {
          console.log(docs)
            res.render('cart',{
              carts:docs,
              title:'购物车商品'
            });
        });
    
});
//添加购物车商品
router.get("/addToCart/:id", middleware.signinRequired, function(req, res, next) {
   //req.params.id 获取商品ID号
        
        Cart.findOne({"uId":req.session.user._id, "cId":req.params.id},function(error,doc){
            //商品已存在 +1
            if(doc){

                Cart.update({"uId":req.session.user._id, "cId":req.params.id},{$set : { cQuantity : doc.cQuantity + 1 }},function(error){
                    //成功返回1  失败返
                    if(error){
                      console.log(error)
                    }else{
                      res.redirect('/home');
                    }
                        
                       
                });
            //商品未存在，添加
            }else{
                Commodity.findOne({"_id": req.params.id}, function (error, doc) {
                    if (doc) {
                        Cart.create({
                            uId: req.session.user._id,
                            cId: req.params.id,
                            cName: doc.name,
                            cPrice: doc.price,
                            cImgSrc: doc.imgSrc,
                            cQuantity : 1
                        },function(error,doc){
                            if(doc){
                                res.redirect('/home');
                                next()
                            }
                        });
                    } else {
                      next()
                    }
                });
            }
        });
    
});

//删除购物车商品
router.get("/delFromCart/:id", function(req, res) {
    //req.params.id 获取商品ID号
    
    Cart.remove({"_id":req.params.id},function(error,doc){
        //成功返回1  失败返回0

        if(error){
           console.log(err);
        }else{
          res.redirect('/cart');
        }
    });
});

//购物车结算
router.post("/cart/clearing",function(req,res){
    console.log(00000)
    Cart.update({"_id":req.body.cid},{$set : { cQuantity : req.body.cnum, cStatus:true }},function(error,doc){
        //更新成功返回1  失败返回0
        if(doc > 0){
            res.send(200);
        }
    });
});

router.delete('/submitOrder', middleware.signinRequired, function(req,res,next){

        Cart.remove({cStatus:true},function(err,cart){
            if(err){
               console.log(err);
            }else{
                res.json({success:1});
            }
        });
  
})

router.get('/home', function (req, res) {
    
        
        Commodity.find({}, function (error, docs) {
            res.render('home',{
              Commoditys:docs,
              title:'商品页'
            });
        });
    
});
router.get('/addcommodity', function(req, res) {

    res.render('addcommodity',{
      title:'添加商品',
      commodity :{
        name:'',
        price:'',
        imgSrc:'',
        summary:''
      } 
    });
});
router.post('/addcommodity', middleware.signinRequired, middleware.adminRequired, middleware.savePoster, function (req, res) {
   

    var id = req.body.id;
    var Obj = req.body;
    var _commodity;
    console.log(req.poster)
      if (req.poster) {
        Obj.imgSrc = req.poster
      }
      if (id) {
        Commodity.findById(id, function(err, commodity) {
          if (err) {
            console.log(err);
          }
          _commodity = _.extend(commodity, Obj);
          
          _commodity.save(function(err, commodity) {
            if (err) {
              console.log(err);
            }
            res.redirect('/home');
          });
        });
      } else {
        _commodity = new Commodity({
          name: Obj.name,
          price: Obj.price,
          imgSrc: Obj.imgSrc,
          summary: Obj.summary
        });
        _commodity.save(function(err, commodity) {
          if (err) {
            console.log(err);
          }
          res.redirect('/home');
          
        });
      }
});

//删除商品
router.delete('/commoditylist',middleware.signinRequired, middleware.adminRequired, function(req,res,next){
  var id = req.query.id;
  
    if(id){
        Commodity.remove({_id:id},function(err,travel){
            if(err){
               console.log(err);
            }else{
                res.json({success:1});
            }
        });
    }
  
})

//商品列表页
router.get('/commoditylist',middleware.signinRequired, middleware.adminRequired, function(req, res, next) {
  
    Commodity.fetch(function(err, Commodity) {
      if(err){
        console.log(err)
      }
      res.render('Commoditylist', {
        title: '商品列表页',
        commodity: Commodity
      });
    })
  
});

//admin update commodity
router.get('/commodityUpdate/:id',middleware.signinRequired, middleware.adminRequired, function(req, res, next){
  var id =req.params.id
  
    if(id) {
      Commodity.findById(id, function(err, commodity){
        res.render('addcommodity', {
          title: '商品更新页',
          commodity: commodity
        })
      })
    }
  
})

//商品详情页
router.get('/commodity/:id', function(req, res, next) {
  
  var id = req.params.id

  Commodity.findById(id, function(err, commodity) {
    if(err){
      console.log(err)
    }
    res.render('commodityDetail', { 
      title: '商品详情页',
      commodity: commodity
    })
    
    
  })
  
});

//订单
//
router.post('/submitOrder', function(req, res, next){
  
  Cart.find({"uId":req.session.user._id,"cStatus": true}, function (error, docs) {
      
      if(docs){
        var _order = new Order({
          uId: req.session.user._id,
          uName: req.session.user.name,
          ordername: req.body.ordername,
          location: req.body.location,
          tel: req.body.tel,
          total: req.body.total,
          cart: docs 
        });
        _order.save(function(err, order){
          if(err){
            console.log(err)
          }
          Cart.remove({"uId":req.session.user._id,"cStatus":true},function(err, docs){
            res.redirect('/order/' + order._id)
          });
          
          
          
          
        })

      }
      

  });
  
})

router.get('/order/:id', function(req, res, next) {
  
  var id = req.params.id

  Order.findById(id, function(err, order) {
    if(err){
      console.log(err)
    }
    res.render('pay', { 
      title: '支付页',
      order: order
    })
    
    
})
  
});
//确认付款
router.get('/payover/:id' ,function(req,res, next){

    var id = req.params.id;
    Order.update({"_id": id},{$set : { 'pay':true}},function(error,doc){
        //更新成功返回1  失败返回0
        if(error){
          console.log(error)
        }
        res.redirect('/orderlist');
    });
});
router.get('/submitOrder', function(req, res, next) {

   Cart.find({"uId":req.session.user._id,"cStatus":true}, function (error, docs) {
       
        res.render('submitOrder',{
          carts:docs,
          title:'提交订单'
        });
    });
});
router.delete('/submitCart', middleware.signinRequired, function(req,res,next){
        
        Cart.remove({"uId":req.session.user._id,"cStatus":true},function(err,cart){
            if(err){
               console.log(err);
            }else{
                res.json({success:1});
            }
        });
  
})

router.get('/orderlist', function(req, res, next) {

  var user = req.session.user
  
  if (user.role == 1) {
    Order.fetch(function(err, orders){
      if (err) {
        console.log(err)
      }
      res.render('orderlist', { 
        title: '订单列表', 
        orders: orders

      })
    })
  }else if(user.role == 0){
    Order.find({"uId":req.session.user._id}, function (err, orders) {
        if (err) {
          console.log(err)
        }
        res.render('orderlist',{
          title: '订单列表', 
          orders:orders
        });
    });
  }
   
});
//确认收货
router.get('/confirmOrder/:id' ,function(req,res, next){
    var id = req.params.id;
    Order.update({"_id": id},{$set : {cStatus:1 }},function(error,doc){
        //更新成功返回1  失败返回0
        if(error){
          console.log(error)
        }
        res.redirect('/orderlist');
    });
});
//取消订单
router.get('/concelOrder/:id' ,function(req,res, next){
    var id = req.params.id;
    Order.update({"_id": id},{$set : {cStatus:2 }},function(error,doc){
        //更新成功返回1  失败返回0
        if(error){
          console.log(error)
        }
        res.redirect('/orderlist');
    });
});

module.exports = router;
